﻿using System;
using System.Collections.Generic;
using System.Text;

namespace MergeHosts.HostsImpt
{
    public class OutInMerge : IMergeHosts
    {
        public void Merge(string oldFile, string newFile)
        {
            // 读系统Hosts文件
            Dictionary<string, string> sysMapping = MergeFacade.GetIpHostMapping(oldFile);
            Dictionary<string, string> sysMappingCopy = new Dictionary<string, string>(sysMapping);
            // 读新的Hosts文件
            Dictionary<string, string> newMapping = MergeFacade.GetIpHostMapping(newFile);

            foreach (KeyValuePair<string, string> pair in newMapping)
            {
                if (sysMappingCopy.ContainsKey(pair.Key))
                {
                    sysMapping[pair.Key] = newMapping[pair.Key];
                }
                else
                {
                    sysMapping.Add(pair.Key, pair.Value);
                }
            }

            foreach (KeyValuePair<string, string> pair in sysMappingCopy)
            {
                if (!newMapping.ContainsKey(pair.Key))
                {
                    sysMapping.Remove(pair.Key);
                }                
            }
            // 写Hosts
            MergeFacade.WriteHosts(oldFile, sysMapping);
        }
    }
}
